<template>
  <div class="admin-home-container">
    <el-container>
      <el-header class="admin-header">
        <div class="header-title">后台管理系统</div>
        <div class="user-info">
          <span>管理员</span>
          <el-button type="primary" icon="Logout" @click="logout">退出登录</el-button>
        </div>
      </el-header>
      <el-container>
        <el-aside width="200px" class="admin-aside">
          <el-menu
            default-active="1"
            class="el-menu-vertical-demo"
            @select="handleMenuSelect"
          >
            <el-menu-item index="1">
              <el-icon><User /></el-icon>
              <span>用户管理</span>
            </el-menu-item>
            <el-menu-item index="2">
              <el-icon><Ticket /></el-icon>
              <span>维修单管理</span>
            </el-menu-item>
            <el-menu-item index="3">
              <el-icon><Monitor /></el-icon>
              <span>设备管理</span>
            </el-menu-item>
          </el-menu>
        </el-aside>
        <el-main class="admin-main" >
          <el-tabs v-model="activeTab" type="border-card">
            <el-tab-pane label="用户管理" name="user" disabled="true">
              <div class="user-list-container">
                <div class="user-list-title">用户管理</div>
                <div class="search-bar">
                  <el-input v-model="userSearchQuery" placeholder="请输入用户名搜索" class="search-input">
                    <template #append>
                      <el-button type="primary" @click="fetchUsers1">搜索</el-button>
                    </template>
                  </el-input>
                </div>
                <el-table :data="userList" style="width: 100%">
                  <el-table-column prop="username" label="用户名"></el-table-column>
                  <el-table-column label="身份" width="120">
                    <template #default="scope">
                      {{ getIdentityText(scope.row.role) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="150" fixed="right">
                    <template #default="scope">
                      <el-button size="small" type="danger" @click="deleteUser(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-tab-pane>
            <el-tab-pane label="维修单管理" name="workorder" disabled="true">
              <div class="workorder-list-container">
                <div class="workorder-list-title">维修单管理</div>
                <div class="search-bar">
                  <el-input v-model="workorderSearchQuery" placeholder="设备编号搜索" class="search-input">
                    <template #append>
                      <el-button type="primary" @click="fetchWorkorders1">搜索</el-button>
                    </template>
                  </el-input>
                </div>
                <el-table :data="workorderList" style="width: 100%">
                  <el-table-column prop="orderId" label="工单编号" width="100"></el-table-column>
                  <el-table-column prop="deviceCode" label="设备编号" width="120"></el-table-column>
                  <el-table-column prop="userId" label="用户名称"></el-table-column>
                  <el-table-column prop="description" label="故障描述"></el-table-column>
                  <el-table-column prop="status" label="工单状态" width="100">
                    <template #default="scope">
                      <el-tag :type="getStatusTagType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="rating" label="用户打分"></el-table-column>
                  <el-table-column prop="feedback" label="用户评价"></el-table-column>
                  <el-table-column prop="repairmanId" label="维修人员" width="120"></el-table-column>
                  <el-table-column prop="createTime" label="提交时间" width="180"></el-table-column>
                  <el-table-column label="操作" width="200" fixed="right">
                    <template #default="scope">
                      <el-button size="small" type="primary" @click="editWorkorder(scope.row)">编辑</el-button>
                      <el-button size="small" type="danger" @click="deleteWorkorder(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-tab-pane>
            <el-tab-pane label="设备管理" name="device" disabled="true">
              <div class="device-list-container">
                <div class="device-list-title">设备管理</div>
                <div class="search-bar">
                  <el-input v-model="deviceSearchQuery" placeholder="请输入设备名称或型号搜索" class="search-input">
                    <template #append>
                      <el-button type="primary" @click="fetchDevices1">搜索</el-button>
                    </template>
                  </el-input>
                    <el-button type="primary" @click="showAddDeviceDialog">新增设备</el-button>
                </div>
                <el-table :data="deviceList" style="width: 100%">
                  <el-table-column prop="deviceId" label="设备ID" width="80"></el-table-column>
                  <el-table-column prop="deviceCode" label="设备编号"></el-table-column>
                  <el-table-column prop="model" label="设备型号" width="120"></el-table-column>
                  <el-table-column prop="status" label="设备状态" width="100">
                    <template #default="scope">
                      <el-tag :type="getDeviceStatusTagType(scope.row.status)">{{ getDeviceStatusText(scope.row.status) }}</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="200" fixed="right">
                    <template #default="scope">
                      <el-button size="small" type="primary" @click="editDevice(scope.row)">编辑</el-button>
                      <el-button size="small" type="danger" @click="deleteDevice(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-tab-pane>
          </el-tabs>

        <!-- 编辑维修单弹窗 -->
        <el-dialog v-model="editWorkorderDialogVisible" title="编辑维修单" width="500px" teleport="body" :z-index="1000">
          <el-form :model="editWorkorderForm" label-width="100px">
            <el-form-item label="设备编号" prop="deviceCode">
              <el-input v-model="editWorkorderForm.deviceCode" placeholder="请输入设备编号"></el-input>
            </el-form-item>
            <el-form-item label="维修人员ID" prop="repairmanId">
              <el-input v-model="editWorkorderForm.repairmanId" placeholder="请输入维修人员"></el-input>
            </el-form-item>
            <el-form-item label="工单状态" prop="status">
              <el-select v-model="editWorkorderForm.status" placeholder="请选择工单状态">
                <el-option label="待处理" value="pending"></el-option>
                <el-option label="处理中" value="processing"></el-option>
                <el-option label="已完成" value="completed"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="editWorkorderDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveEditWorkorder">确认</el-button>
          </template>
        </el-dialog>

        <!-- 编辑设备弹窗 -->
        <el-dialog v-model="editDeviceDialogVisible" title="编辑设备" width="500px">
          <el-form :model="editDeviceForm" label-width="100px">
            <el-form-item label="设备编号" prop="deviceCode" required>
              <el-input v-model="editDeviceForm.deviceCode" placeholder="请输入设备编号"></el-input>
            </el-form-item>
            <el-form-item label="设备型号" prop="model" required>
              <el-input v-model="editDeviceForm.model" placeholder="请输入设备型号"></el-input>
            </el-form-item>
            <el-form-item label="设备状态" prop="status">
              <el-select v-model="editDeviceForm.status" placeholder="请选择设备状态">
                <el-option label="正常" value="0"></el-option>
                <el-option label="维修中" value="1"></el-option>
                <el-option label="已完成" value="2"></el-option>
                <el-option label="维修失败" value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="editDeviceDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveEditDevice">确认</el-button>
          </template>
        </el-dialog>

        <!-- 新增设备弹窗 -->
        <el-dialog v-model="addDeviceDialogVisible" title="新增设备" width="500px">
          <el-form :model="newDevice" label-width="100px">
            <el-form-item label="设备编号" prop="deviceCode" required>
              <el-input v-model="newDevice.deviceCode" placeholder="请输入设备编号"></el-input>
            </el-form-item>
            <el-form-item label="设备型号" prop="model" required>
              <el-input v-model="newDevice.model" placeholder="请输入设备型号"></el-input>
            </el-form-item>
            <el-form-item label="设备状态" prop="status">
              <el-select v-model="newDevice.status" placeholder="请选择设备状态">
                <el-option label="正常" value="0"></el-option>
                <el-option label="维修中" value="1"></el-option>
                <el-option label="已完成" value="2"></el-option>
                <el-option label="维修失败" value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="addDeviceDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="addDevice">确认</el-button>
          </template>
        </el-dialog>

        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { removeToken, getToken } from '~/composables/auth';
import { toast, showModal } from '~/composables/util';
import { User, Ticket, Monitor } from '@element-plus/icons-vue';
import service from '~/axios';

const router = useRouter();


const activeTab = ref('user');

// 用户管理相关变量
const userList = ref([]);
const userSearchQuery = ref('');

// 维修单管理相关变量
const workorderList = ref([]);
const workorderSearchQuery = ref('');

// 设备管理相关变量
const deviceList = ref([]);
const deviceSearchQuery = ref('');

onMounted(() => {
  if (!getToken()) {
    toast('请先登录', 'warning');
    router.push('/admin-login');
    return;
  }
  fetchUsers();
});

const handleMenuSelect = (index) => {
  switch (index) {
    case '1':
      activeTab.value = 'user';
      fetchUsers();
      break;
    case '2':
      activeTab.value = 'workorder';
      fetchWorkorders();
      break;
    case '3':
      activeTab.value = 'device';
      fetchDevices();
      break;
  }
};

// 用户身份映射
const getIdentityText = (identity) => {
  // 确保identity是数字类型
  const numIdentity = Number(identity);
  const identityMap = {
    0: '普通用户',
    1: '维修工',
    2: '管理者'
  };
  
  return identityMap[numIdentity] || '未知身份';
};

// 用户管理相关方法
const fetchUsers = async () => {
    console.log('开始获取用户列表...');
    const res = await service.get('/admin/users');
    console.log('获取用户列表成功:', res);
      console.log('res.data:', res.data);
      console.log('res.data.data:', res.data.data);
  
    let data = res.data.data;
    if (data && !Array.isArray(data)) {
        data = [data]; 
    }
    userList.value = Array.isArray(data) ? data : [];
};
const fetchUsers1= async () => {
    console.log('开始获取用户...');
    const res = await service.get('/admin/users/search',{
        params: {
            username: userSearchQuery.value
        }
    });
    console.log('获取用户列表成功:', res);
    let data = res.data.data;
    if (data && !Array.isArray(data)) {
        data = [data]; 
    }
    userList.value = Array.isArray(data) ? data : [];
    console.log(userList.value);
};


const deleteUser = async (row) => {
  try {
    await showModal(`确定要删除用户${row.username}?`, 'danger');
    await service.delete('/admin/users', { params: { username: row.username } });
    toast('删除成功');
    fetchUsers();
  } catch (error) {
    toast('删除失败，请稍后重试', 'error');
  }
};

// 维修单管理相关方法
const fetchWorkorders = async () => {
  try {
    const res = await service.get('/admin/orders');
    console.log(res.data.data);
    workorderList.value = res.data.data || [];
  } catch (error) {
    toast('获取维修单列表失败，请稍后重试', 'error');
  }
};
const fetchWorkorders1 = async () => {
  try {
    const res = await service.get('/admin/orders/search',{params: {
        deviceCode: workorderSearchQuery.value
      }});
    console.log(res.data.data);
    workorderList.value = res.data.data || [];
  } catch (error) {
    toast('获取维修单列表失败，请稍后重试', 'error');
  }
};

const getStatusText = (status) => {
  const numStatus = Number(status);
  const statusMap = {
    0: '待处理',
    1: '处理中',
    2: '已完成',
    3: '已取消'
  };
  return statusMap[numStatus] || '未知状态';
};

const getStatusTagType = (status) => {
  const numStatus = Number(status);
  const typeMap = {
    0: 'info',
    1: 'warning',
    2: 'success',
    3: 'danger'
  };
  return typeMap[numStatus] || 'default';
};



// 编辑维修单弹窗相关
const editWorkorderDialogVisible = ref(false);
const editWorkorderForm = ref({});

const editWorkorder = (row) => {
  console.log('尝试显示编辑维修单弹窗');
  // 加载当前工单数据到编辑表单
  editWorkorderForm.value = { ...row };
  editWorkorderDialogVisible.value = true;
  console.log('editWorkorderDialogVisible状态:', editWorkorderDialogVisible.value);
};



const deleteWorkorder = async (row) => {
  try {
    await showModal(`确定要删除工单 ${row.orderId}?`, 'danger');
    await service.delete('/admin/orders', { params: { orderId: row.orderId } });
    toast('删除成功');
    fetchWorkorders();
  } catch (error) {

  }
};

// 设备状态映射
const getDeviceStatusText = (status) => {
  const numStatus = Number(status);
  const statusMap = {
    0: '正常',
    1: '维修中',
    2: '已完成',
    3: '维修失败'
  };
  return statusMap[numStatus] || '未知状态';
};

const getDeviceStatusTagType = (status) => {
  const numStatus = Number(status);
  const typeMap = {
    0: 'success',
    1: 'warning',
    2: 'info',
    3: 'danger'
  };
  return typeMap[numStatus] || 'default';
};

// 设备管理相关方法
const fetchDevices = async () => {
  try {
    const res = await service.get('/admin/devices');
    deviceList.value = res.data.data || [];
    console.log(deviceList.value);
  } catch (error) {
    toast('获取设备列表失败，请稍后重试', 'error');
  }
};
const fetchDevices1 = async () => {
  try {
    const res = await service.get('/admin/devices/search',{params: {
        deviceCode: deviceSearchQuery.value
      }});
    let data = res.data.data;
    // 确保数据是数组类型
    if (data && !Array.isArray(data)) {
      data = [data];
    }
    deviceList.value = Array.isArray(data) ? data : [];
  } catch (error) {
    toast('获取设备列表失败，请稍后重试', 'error');
  }
};



// 编辑设备弹窗相关
const editDeviceDialogVisible = ref(false);
const editDeviceForm = ref({});

const editDevice = (row) => {
  console.log('尝试显示编辑设备弹窗');
  // 加载当前设备数据到编辑表单
  editDeviceForm.value = { ...row };
  editDeviceDialogVisible.value = true;
  console.log('editDeviceDialogVisible状态:', editDeviceDialogVisible.value);
};

const saveEditDevice = async () => {
  try {
    if (!editDeviceForm.value.deviceCode) {
      toast('设备编号不能为空', 'warning');
      return;
    }
    if (!editDeviceForm.value.model) {
      toast('设备型号不能为空', 'warning');
      return;
    }

    await service.put('admin/devices', editDeviceForm.value);
    toast('编辑成功');
    editDeviceDialogVisible.value = false;
    fetchDevices();
  } catch (error) {
    toast('编辑失败，请稍后重试', 'error');
  }
};
// 新增设备弹窗相关
const addDeviceDialogVisible = ref(false);
const newDevice = ref({
  deviceCode: '',
  model: '',
  status: 0 // 0=正常，1=维修中,2=已完成,3=维修失败
});

const showAddDeviceDialog = () => {
  addDeviceDialogVisible.value = true;
};

const saveEditWorkorder = async () => {
  try {

    const statusMap = {
      'pending': 1,
      'processing': 2,
      'completed': 3,
      'cancelled': 0
    };

    const status = statusMap[editWorkorderForm.value.status] || 1; // 默认1

    await service.put('admin/orders/status', null, {
      params: {
        orderId: editWorkorderForm.value.orderId,
        status: status,
        deviceCode: editWorkorderForm.value.deviceCode,
        repairmanId: editWorkorderForm.value.repairmanId
      }
    });

    toast('编辑成功');
    editWorkorderDialogVisible.value = false;
    fetchWorkorders();
  } catch (error) {
    toast('编辑失败，请稍后重试', 'error');
  }
};

const addDevice = async () => {
  try {
    if (!newDevice.value.deviceCode) {
      toast('设备编号不能为空', 'warning');
      return;
    }
    if (!newDevice.value.model) {
      toast('设备型号不能为空', 'warning');
      return;
    }
    
    await service.post('admin/devices', newDevice.value);
    toast('新增成功');
    addDeviceDialogVisible.value = false;
    fetchDevices();
    // 重置表单
    newDevice.value = {
      deviceCode: '',
      model: '',
      status: 0
    };
  } catch (error) {
    toast('新增失败，请稍后重试', 'error');
  }
};

// 保留原有的deleteDevice函数
const deleteDevice = async (row) => {
  try {
    await showModal(`确定要删除设备 ${row.deviceCode}?`, 'danger');
    await service.delete('admin/devices', { params: { deviceId: row.deviceId } });
    toast('删除成功');
    fetchDevices();
  } catch (error) {
    // 用户取消删除
  }
};

const changeDeviceStatus = async (row) => {
  try {
    // 将字符串状态映射为后端需要的整数值
    const statusMap = {
      'normal': 0,
      'faulty': 1
    };
    const status = statusMap[row.status] || 0;

    await service.put('admin/devices', {
      deviceId: row.deviceId,
      deviceCode: row.deviceCode,
      model: row.model,
      status: status
    });
    toast('状态已更新');
  } catch (error) {
    // 恢复原来的状态
    row.status = row.status === 'normal' ? 'faulty' : 'normal';
    toast('更新状态失败，请稍后重试', 'error');
  }
};

const logout = () => {
  removeToken();
  toast('已退出登录');
  router.push('/login');
};
</script>

<style scoped>
.admin-home-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.admin-header {
  background-color: #409eff;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.header-title {
  font-size: 20px;
  font-weight: bold;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.admin-aside {
  background-color: #f0f2f5;
}

.admin-main {
  padding: 20px;
  background-color: #f5f5f5;
  overflow: auto;
  z-index: 1;
}

/* 用户管理样式 */
.user-list-container {
  padding: 20px;
}

.user-list-title {
  font-size: 24px;
  margin-bottom: 20px;
  color: #333;
}

.search-bar {
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

/* 维修单管理样式 */
.workorder-list-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.workorder-list-title {
  font-size: 20px;
  margin-bottom: 20px;
  color: #333;
}

.workorder-list-container .search-bar {
  display: flex;
  gap: 10px;
  align-items: center;
}

.workorder-list-container .pagination {
  display: flex;
  justify-content: flex-end;
}

/* 设备管理样式 */
.device-list-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.device-list-title {
  font-size: 20px;
  margin-bottom: 20px;
  color: #333;
}

.device-list-container .search-bar {
  display: flex;
  gap: 10px;
  align-items: center;
}

.device-list-container .pagination {
  display: flex;
  justify-content: flex-end;
}

.add-btn {
  white-space: nowrap;
}
</style>
